package utils

import (
	"crypto/tls"
	"fmt"
	"net"
	"net/smtp"
	"sport_booking/config"
	"sport_booking/utils/message"
)

func SendMail(nick, title, body string, to string) int {
	header := map[string]string{}
	header["From"] = nick + "<" + config.MailUser + ">"
	header["To"] = to
	header["Subject"] = title
	header["Content-Type"] = "text/html;charset=UTF-8"
	message := ""
	for k, v := range header {
		message += fmt.Sprintf("%s:%s\r\n", k, v)
	}
	message += "\r\n" + body

	return setMailByTLS([]string{to}, []byte(message))

}
func setMailByTLS(to []string, msg []byte) int {
	// create smtp client
	addr := fmt.Sprintf("%s:%d", config.MailHost, config.MailPort)
	c, err := tcpDial(addr)
	if err != nil {
		return message.ErrorEmailDial
	}
	auth := smtp.PlainAuth("", config.MailUser, config.MailPassword, config.MailHost)
	if auth != nil {
		if ok, _ := c.Extension("AUTH"); ok {
			if err = c.Auth(auth); err != nil {
				return message.ErrorEmailAuthUser
			}
		}
	}
	if err = c.Mail(config.MailUser); err != nil {
		return message.ErrorEmailCallMail
	}
	for _, addr := range to {
		if err = c.Rcpt(addr); err != nil {
			return message.ErrorEmailCallRcpt
		}
	}
	w, err := c.Data()
	if err != nil {
		return message.ErrorEmailCallData
	}
	_, err = w.Write(msg)
	if err != nil {
		return message.ErrorEmailWriteStream
	}
	err = w.Close()
	if err != nil {
		return message.ErrorEmailCloseWriteStream
	}
	err = c.Quit()
	if err != nil {
		return message.ErrorEmailCloseServer
	}
	return message.SUCCESS
}

// return a smtp client
func tcpDial(addr string) (*smtp.Client, error) {
	conn, err := tls.Dial("tcp", addr, nil)
	if err != nil {
		return nil, err
	}
	// 分解主机端口字符串
	host, _, _ := net.SplitHostPort(addr)
	return smtp.NewClient(conn, host)
}
